package com.bodacn.packapp;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import androidx.appcompat.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class DetailActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    Toast curToast;
    String PhotoUrl="";
    Button btn_find,btn_return;
    private TextView edit_startDate, edit_endDate, edit_orderNo, edit_styleNo;
    ListView detailListGrid;
    JSONArray detailJSON;
    //全局变量
    private ProgressDialog waitDialog = null;
    String curServiceUrl="",curLoginUserNo="",curLoginUser="",curOrderNo="",curVatNo="",curPullFormNo="",curCutSerial="",packType="";

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (waitDialog!=null) waitDialog.dismiss();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        //创建对话框，
        waitDialog=new ProgressDialog(DetailActivity.this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        PhotoUrl=paramBundle.getString("PhotoUrl");
        curOrderNo=paramBundle.getString("CurOrderNo");
        curVatNo=paramBundle.getString("CurVatNo");
        curCutSerial=paramBundle.getString("CurCutSerial");
        curPullFormNo=paramBundle.getString("CurPullFormNo");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        packType=paramBundle.getString("packType");
        System.out.println("onCreate-------------"+curOrderNo+":"+curPullFormNo+":"+curCutSerial);
        //初始化界面
        InitView();
    }




    private void InitView(){
        btn_find=(Button)findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_return=(Button)findViewById(R.id.btn_return);
        btn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("onClick","准备关闭");
                //关闭当前Activity;
                finish();
            }
        });
        //文本框
        edit_startDate = (EditText) findViewById(R.id.edit_startDate);
        edit_startDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(DetailActivity.this, null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_startDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询起始日期");
                mDialog.show();

            }
        });
        edit_startDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        edit_endDate = (EditText) findViewById(R.id.edit_endDate);
        edit_endDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(DetailActivity.this, null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_endDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询截止日期");
                mDialog.show();
            }
        });
        edit_orderNo = (EditText) findViewById(R.id.edit_orderNo);
        edit_orderNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_orderNo","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        edit_orderNo.setOnKeyListener(new EditText.OnKeyListener(){
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode==66)
                {
                    hideIM(v);
                    btn_find.setFocusable(true);
                    btn_find.setFocusableInTouchMode(true);
                    btn_find.requestFocus();
                    btn_find.requestFocusFromTouch();
                }
                return false;
            }
        });

        edit_styleNo = (EditText) findViewById(R.id.edit_styleNo);
        edit_styleNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        edit_styleNo.setOnKeyListener(new EditText.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode==66)
                {
                    hideIM(v);
                    btn_find.setFocusable(true);
                    btn_find.setFocusableInTouchMode(true);
                    btn_find.requestFocus();
                    btn_find.requestFocusFromTouch();
                }
                return false;
            }
        });
        //表格;
        detailListGrid = (ListView) findViewById(R.id.detailListGrid);
        detailListGrid.setOnItemClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        String StartDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime() -1 * 24 * 60 * 60 * 1000));
        String EndDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edit_startDate.setText(StartDateStr);
        edit_endDate.setText(EndDateStr);
    }


    //刷新缸布列表;
    private void refreshDetailData(String startDateParam,String endDateParam,String orderNoParam,String styleNoParam)
    {
        try {
            detailJSON=new JSONArray("[]");
            //显示到orderListGrid中;
            final DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            detailListGrid.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        waitDialog.setMessage("正在获取明细数据，请稍等...");
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec PackPAD_GetDetail @StartDate='" + startDateParam + "',@EndDate='" + endDateParam + "',@OrderNo='" + orderNoParam + "',@StyleNo='"+styleNoParam+ "',@PackType='" + packType+"',@UserNo='"+curLoginUserNo+"'");
        //调用WebService过程并处理界面更新;
        ReadSQLData(curServiceUrl, methodName, paramMap);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_find:
                if (edit_startDate.getText().length()==0||edit_endDate.getText().length()==0) {
                    curToast.setText("请选择查询的日期条件!");
                    curToast.show();
                } else refreshDetailData(edit_startDate.getText().toString(),edit_endDate.getText().toString(),edit_orderNo.getText().toString(),edit_styleNo.getText().toString());
                break;
            case R.id.btn_PDF:
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent==detailListGrid)
        {
            view.setSelected(true);
        }
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.detail_item, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(60)));
            int color = getResources().getColor(R.color.black);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.text_detail_packDepart);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("packDepart").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_orderNo);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("orderNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_PO);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("PO").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_color);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("color").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_size);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("size").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_custColor);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("custColor").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_needNum);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("needNum").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_sendNum);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("sendNum").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_callTime);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("callTime").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_sendTime);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("sendTime").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.text_detail_totalNeedNum);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("totalNeedNum").toString());
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }


    public void ReadSQLData(String serviceUrl,String methodName,Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                waitDialog.show();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                Boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                //置参数给对象
                String namespace="http://tempuri.org/";
                SoapObject soapObject=new SoapObject(namespace, methodName);
                SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
                //遍列Map数组加参数
                Map<String,Object> paramMap= (Map<String,Object>) params[0].get("paramMap");
                Iterator iterator = paramMap.keySet().iterator();
                while (iterator.hasNext())
                {
                    String paramkey = (String) iterator.next();
                    String paramvalue = (String) paramMap.get(paramkey);
                    soapObject.addProperty(paramkey,paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                }
                //准备执行WebService
                envelope.dotNet=true;
                envelope.setOutputSoapObject(soapObject);
                HttpTransportSE httpTranstation=new HttpTransportSE(serviceUrl,10000);
                try {
                    //执行调用WebService;
                    httpTranstation.call(namespace+methodName, envelope);
                    //获取返回会值;
                    Object result=envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr=(String) result.toString();
                    System.out.println(resultstr);
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (XmlPullParserException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true) Log.d("msg","查询数据出错,错误异常抛出！");
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null)
                {
                    if (waitDialog.equals(null)==false) waitDialog.hide();
                    return;
                }
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    System.out.println("接收到的内容:"+s);
                    JSONArray jsonArray = new JSONArray(s);
                    //往界面转数据;
                    if (jsonArray.length()>0) {
                            detailJSON = jsonArray;
                            //显示预排单;
                            final DetailListAdapter detailListAdapter = new DetailListAdapter(getApplicationContext());
                            detailListGrid.setAdapter(detailListAdapter);
                    }
                    //关闭ProgressDialog
                    waitDialog.hide();
                } catch (JSONException e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    waitDialog.hide();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }
        }.execute(params);

    }
}
